<?php

namespace App\Services\Cache;

use App\Models\VipCategory;
use App\Models\VipWelfare;
use App\Models\Product;
use App\Models\VipWelfareDetailRelationProduct;
use App\Models\VipWelfareDetailRelationCoupon;
use Illuminate\Support\Facades\Cache;

class VipWelfareCache
{
	
	public function welfares($id)
	{
		$key = url()->full();
		$list = Cache::remember($key, 1, function () use ($id) {
			$welfares = VipWelfare::query()
						->with('welfareDetails')
						->where('vip_category_id',$id)
						->orderBy("order")
						->get();
			$list = [];	
			foreach($welfares as $k=>$v){
				$list[$k]['id'] = $v->id;
				$list[$k]['name'] = $v->name;
				$list[$k]['is_radio'] = $v->is_radio;
				$list[$k]['details'] = [];
				if($v->welfareDetails){
					foreach($v->welfareDetails as $key => $value){
						$list[$k]['details'][$key]['type'] = $value->type;
						$list[$k]['details'][$key]['welfare_id'] = $value->id;

						if($value->type == 'phone'){
							$list[$k]['details'][$key]['phone_bill_name'] = $value->phone_bill_name;
							$list[$k]['details'][$key]['cost'] = $value->cost;
						}elseif($value->type == 'drink'){
							$list[$k]['details'][$key]['product'] = Product::query()->where('id',$value->product_id)->first()
										->toArray();
							
						}elseif($value->type == 'product'){
							$products = VipWelfareDetailRelationProduct::query()
										->join('products','products.id','vip_welfare_detail_relation_products.product_id')
										->where('vip_welfare_detail_id',$value->id)
										->get()
										->toArray();

							$list[$k]['details'][$key]['products'] = $products;

						}elseif($value->type == 'coupon'){
							$coupons = VipWelfareDetailRelationCoupon::query()
										->join('coupons','coupons.id','vip_welfare_detail_relation_coupons.coupon_id')
										->where('vip_welfare_detail_id',$value->id)
										->get()
										->toArray();

							$list[$k]['details'][$key]['coupons'] = $coupons;

						}

					}

				}
			}
			return $list;
		
		});
		return $list;
	}
	
}
